﻿using System;
using System.Collections.Generic;
using ComLib.Apps.FluentSharp.Lib.Entities;
using ComLib.Lang;
using ComLib.Lang.Types;

namespace ComLib.Apps.FluentSharp.Lib.Utilities
{
    public class ResultsCheck
    {
        
        public static void CheckExpectedResults(Interpreter ip, string fileContent, Script script, ScriptResult result)
        {
            // Load the expected results from filecontent... if they are there.
            LoadExpectedResults(fileContent, script, result);

            // Check that each expected result is correct.
            for (int z = 0; z < script.ExceptedValues.Count; z++)
            {
                var resultData = new ExpectedData();
                var exceptedValue = script.ExceptedValues[z];
                // Result after executing a script

                object actualValue = ip.Memory.Get<object>(exceptedValue.Name);
                actualValue = ((LObject)actualValue).GetValue();

                // Check if the expected value matched
                resultData.Actual = actualValue.ToString();
                resultData.Expected = exceptedValue.Value;
                resultData.Name = exceptedValue.Name;
                resultData.IsMatched = FluentHelper.IsMatchingValue(actualValue, exceptedValue.DataType, exceptedValue.Value);

                // The script result is a failure if at least 1 of the expected results fails.
                if (resultData.IsMatched)
                {
                    //Console.WriteLine(exceptedValue.Name + " matched : " + actualValue.ToString() + " with : " + exceptedValue.Value);
                }
                else
                {
                    result.Succeed = false;
                    //Console.WriteLine(exceptedValue.Name + " did not match");
                }

                result.ExpectedResults.Add(resultData);
            }
        }


        private static void LoadExpectedResults(string fileContent, Script script, ScriptResult result)
        {
            // If config does not have <expected results> for script..
            // then look at the top of the script.
            if (script.ExceptedValues == null || script.ExceptedValues.Count == 0)
            {
                if (fileContent.StartsWith("/* @hasexpects = true"))
                {
                    var expectedValues = XmlHelper.GetExpectedResultsFromFile(fileContent);
                    script.ExceptedValues = expectedValues;
                }
            }
        }
    }
}
